<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/3
 * Time: 下午6:14
 */

namespace App\HttpController;

use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Core\Swoole\ServerManager;

class Common extends Controller
{

    /**
     * 默认index路径的结果返回
     */
    public function index()
    {
        $this->actionNotFound('index');
    }


    /**
     * 挡在控制器中解析出方法，但没有具体的实现时，调用该方法
     * @param $action
     */
    protected function actionNotFound($action): void
    {
        $this->response()->withStatus(Status::CODE_NOT_FOUND);
        $this->response()->write("{$action} is not exist");
    }

    /**
     * 用于权限检测、认证
     * @param $action
     * @return bool|null
     */
    protected function onRequest($action):?bool
    {
        // token 来源：query,post,header-Authentication
        $token = $this->request()->getRequestParam('token');
        if (!$token) $token = $this->request()->getHeader('Authentication');

        if (!$token) {
            $this->data_encode(null, 40001);
            return false;
        }

        $this->session()->sessionId($token);
        $this->session()->sessionStart();
        if (!$this->session()->get('userinfo')) {
            $this->data_encode(null, 40002);
            return false;
        }

        return true;
        // return parent::onRequest($action);
    }



    // onRequest 控制器名解析出来后，最先执行的方法，true则继续执行，可用于权限验证
    // afterAction 控制器执行结束后，会执行该方法，用于分析记录


    /**
     * 数据发送
     * @param null|array $data 请求成功时的数据
     * @param int $code 请求状态码
     * @param string $message 请求消息
     * @param int $http_code http状态码
     */
    protected function data_encode($data, $code = 0, $message = '', $http_code = 200){
        $res_data = [
            'code'  => $code,
            'msg'   => $message
        ];
        if ($data) {
            $res_data['data'] = $data;
        }

        $this->response()->write(json_encode($res_data));
        $this->response()->end($http_code);
    }
}